/**
 * Created by Administrator on 2017/2/28.
 */

function showPic(whichpic) {
    var source = whichpic.getAttribute("href");
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src", source);
    var text = whichpic.getAttribute("title");
    var description = document.getElementById("description");
    description.firstChild.nodeValue = text;
    description.hidden = false;
}

function preparePlaceholder() {
    if (!document.createElement) return false;
    if (!document.createTextNode) return false;
    if (!document.getElementById) return false;
    if (!document.getElementById("imagegallery")) return false;

    var placeholder = document.createElement("img");
    placeholder.setAttribute("id", "placeholder");
    placeholder.setAttribute("src", "images/placeholder.gif");
    placeholder.setAttribute("alt", "my image gallery");

    var description = document.createElement("p");
    description.setAttribute("id", "description");
    var desctext = document.createTextNode("Choose a image");
    description.appendChild(desctext);

    var gallery = document.getElementById("imagegallery");
    // gallery.parentNode.insertBefore(placeholder, gallery);
    // gallery.parentNode.insertBefore(description, gallery);
    insertAfter(placeholder, gallery);
    insertAfter(description, placeholder)
}

function popup(whichPic) {
    // var source = whichPic.getAttribute("href");
    window.open(whichPic, "Gallery", "width=320,height=480");
}

addLoadEvent(prepareGallery);
addLoadEvent(preparePlaceholder);

function prepareGallery() {
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById) return false;

    var gallery = document.getElementById("imagegallery");
    if (!gallery) return false;

    var links = gallery.getElementsByTagName("a");
    for (var index = 0; index < links.length; index++) {
        // if (links[index].getAttribute("class") == "popup") {
            links[index].onclick = function () {
                popup(this.getAttribute("href"));
                showPic(this)
                return false;
            }
        // }
    }
}

function addLoadEvent(func) {
    var oldOnload = window.onload;
    if (typeof window.onload != "function") {
       window.onload = func;
    } else {
        window.onload = function() {
            oldOnload();
            func();
        }
    }
}
